import Recorder from 'js-audio-recorder'

let rc = null
const start = () => {
  if (rc != null) {
    close()
  }
  rc = new Recorder()
  return rc.start()
}

const pause = () => {
  rc.pause()
}

const close = () => {
  rc.destroy()
  rc = null
}

const upload = () => {
  return new Promise((resolve, reject) => {
    const wavBlob = rc.getWAVBlob()
    const newbolb = new Blob([wavBlob], { type: 'audio/wav' })
    const name = new Date().getDate() + '.wav'
    const file = new File([newbolb], name)
    console.log('file=========', file)
    uni.uploadFile({
      url: '/resource/oss/upload', // 替换为实际的上传接口
      file,
      name: 'file',
      success: (res) => {
        const r = JSON.parse(res.data)
        console.log('r======', r)
        if (r.code === 200) {
          const data = {
            duration: parseInt(rc.duration),
            url: r.data?.url,
          }
          resolve(data)
        } else {
          reject(new Error(r.msg))
        }
      },
      fail: reject,
    })
  })
}

export { start, pause, close, upload }
